package com.cake.liulanxiangzhu.repo.impl;

import com.cake.liulanxiangzhu.pojo.entity.AdminCategory;
import com.cake.liulanxiangzhu.repo.ICategoryRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class CategoryRedisRepositoryImpl implements ICategoryRedisRepository {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public void save(AdminCategory adminCategory) {
        String key = CATEGORY_ITEM_KEY_PREFIX + adminCategory.getCategoryId();
        redisTemplate.opsForSet().add(CATEGORY_ALL_KEYS_KEY, key);
        redisTemplate.opsForValue().set(key,adminCategory);

    }

    @Override
    public void saveList(List<AdminCategory> adminCategories) {
        String key = CATEGORY_LIST_KEY;
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        for (AdminCategory adminCategory : adminCategories) {
            ops.rightPush(key,adminCategory);
        }

    }

    @Override
    public AdminCategory get(Integer categoryId) {
        String key = CATEGORY_ITEM_KEY_PREFIX + categoryId;
        Object vo = redisTemplate.opsForValue().get(key);
        if (vo!=null){
            if (vo instanceof AdminCategory ){
                return (AdminCategory)vo;
            }
        }
        return null;
    }

    @Override
    public List<AdminCategory> getList() {
        String key = CATEGORY_LIST_KEY;
        ListOperations<String, Object> ops = redisTemplate.opsForList();
        Integer start = 0;
        Integer end = 3;
        List<Object> range = ops.range(key, start, end);
        List<AdminCategory> categories = new ArrayList<>();
        for (Object object : range) {
            categories.add((AdminCategory) object);
        }
        return categories;
    }


}
